# _*_ coding:utf-8 _*_
# @Time  : 2022.06.28
# @Author: zizlee
import datetime
import json
from itertools import groupby

import requests
from urllib3 import disable_warnings
from iFinDPy import THS_iFinDLogin, THS_iFinDLogout, THS_DP

disable_warnings()


def split_number_en(ustring):
    return [''.join(list(g)) for k, g in groupby(ustring, key=lambda x: x.isdigit())]


def get_month_contract(q_date):  # 获取期货合约
    # 数据池-板块_板块成分-日期;同花顺代码-iFinD数据接口（境内在交易合约）
    all_contract = THS_DP('block', f'{q_date};091013;monthcontract', 'date:Y,thscode:Y')
    if all_contract.errorcode != 0:
        raise ValueError('获取境内在交易合约失败!{}'.format(all_contract.errorcode))

    # 数据池-板块_板块成分-日期;同花顺代码-iFinD数据接口（国内主力合约）security_name:Y
    main_contract = THS_DP('block', f'{q_date};091012001;monthcontract', 'date:Y,thscode:Y')
    if main_contract.errorcode != 0:
        raise ValueError('获取主力合约失败!{}'.format(all_contract.errorcode))

    all_contracts = all_contract.data.to_dict(orient='records')
    main_contracts =[mc['THSCODE'] for mc in main_contract.data.to_dict(orient='records')]
    today_contracts = []
    for ac in all_contracts:
        contract = ac['THSCODE'].split('.')[0]  # 合约代码
        # 分离合约和代码
        v, c = split_number_en(contract)
        c_item = {
            'contract_date': ac['DATE'].replace('/', '-'),
            'variety_en': v.upper(),
            'ex_code': ac['THSCODE'],
            'lcontract': f'{q_date[2]}{c}' if len(c) < 4 else c,
            'scontract': c,
            'activity': 0 if ac['THSCODE'] in main_contracts else 1
        }
        today_contracts.append(c_item)
    today_contracts.sort(key=lambda x: x['ex_code'])
    save_month_contract(today_contracts)


def save_month_contract(contracts):  # 保存期货合约
    # url = 'http://127.0.0.1:8000/v1/ruizy/variety/updateContract/'
    url = 'https://210.13.218.130:9000/v1/ruizy/variety/updateContract/'
    r = requests.post(url, json=contracts, verify=False)
    print(r.json())


if __name__ == '__main__':
    # 20230417以前的合约除了主力合约以外，有的有错
    with open('../ths.config.json', 'r') as ths:
        ths_configs = json.load(ths)
    ret = THS_iFinDLogin('rdqh085', 'rdrj180912')
    assert ret == 0
    # Q_DATE = (datetime.datetime.today() + datetime.timedelta(days=-1)).strftime('%Y-%m-%d')
    Q_DATE = datetime.datetime.today().strftime('%Y-%m-%d')
    print(Q_DATE)
    # Q_DATE = '2021-02-08'
    get_month_contract(q_date=Q_DATE)
    THS_iFinDLogout()

    # s = datetime.date(2021, 5, 6)
    # while s < datetime.date(2022, 6, 27):
    #     if s.weekday() > 4:
    #         s = s + datetime.timedelta(days=1)
    #         continue
    #     print(s)
    #     get_month_contract(q_date=s.strftime('%Y-%m-%d'))
    #     s = s + datetime.timedelta(days=1)
    # THS_iFinDLogout()



